package org.example.sdpback.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.example.sdpback.domain.entity.User;
import org.example.sdpback.utils.JwtUtil;
import org.example.sdpback.utils.ThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @className: LoginInterceptor
 * @author: zxy
 * @date: 2024/11/3 15:50
 * @Version: 1.0
 * @description: 定义登录拦截器
 **/
@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头token
        String authorization = request.getHeader("Authorization");
        //校验token是否正确
        JwtUtil.checkToken(authorization);
        //解析token
        User tokenUser = JwtUtil.getTokenUser(authorization);

        //校验token有效性,通过redis
        String token = stringRedisTemplate.opsForValue().get(tokenUser.getUsername());
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        if (!token.equals(authorization)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //将tokenUser保存到threadLocal中往下转递
        ThreadLocalUtil.set(tokenUser);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
